const fs = require('fs');
const path = require('path');
const gm = require('gm');

const parser = require('./parser');

// 生成css
function createCSS({ len, width, height }) {
    return `.animate-box {
    width: ${width}px;
    height: ${height}px;
    overflow: hidden;
    background: url(<图片URL>) top left / cover no-repeat;

    &.play {
        animation-name: pngsAnimate;
        animation-duration: ${len} / 40s;   // 这儿可以根据实际帧率调节
        animation-iteration-count: 1;
        animation-timing-function: steps(${len}, end);
    }
}

@keyframes pngsAnimate {
    0% {
        background-position: left;
    }

    100% {
        background-position: right;
    }
}`;
}

// 清除caches目录文件
function removeCacheFile() {
    const cachesDir = path.resolve(__dirname, '../caches');
    const dirents = fs.readdirSync(cachesDir, {
        withFileTypes: true
    });

    dirents.forEach(dirent => {
        if (/\.png$/.test(dirent.name)) {
            fs.unlinkSync(path.join(cachesDir, dirent.name));
        }
    });
}

module.exports = (filePath, outputDir) => new Promise((resolve, reject) => {
    const buf = fs.readFileSync(filePath);
    const imagesArr = parser.apngToPngs(buf);

    if (!Array.isArray(imagesArr) || imagesArr.length === 0) {
        return reject(new Error('not read images'));
    }

    let { width } = imagesArr[0],
        { height } = imagesArr[0];
    imagesArr.forEach(img => {
        if (img.width > width) {
            width = img.width;
        }

        if (img.height > height) {
            height = img.height;
        }
    });

    const gmHandler = gm(width * imagesArr.length, height, '#00FFFFFF');

    imagesArr.forEach((img, i) => {
        if (!fs.existsSync(img.filename)) {
            return reject(new Error(`${img.filename} is not directory`));
        }

        return gmHandler.draw(`image over ${width * i + img.left} ${img.top} ${img.width} ${img.height} "${path.resolve(img.filename)}"`);
    });

    const filename = `output_${Date.now()}.png`;
    const outputFilePath = path.join(outputDir, `./${filename}`);
    return gmHandler.write(outputFilePath, err => {
        if (err) {
            return reject(err);
        }

        removeCacheFile();

        return resolve({
            filename,
            css: createCSS({ len: imagesArr.length, width, height })
        });
    });
});
